/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ddd.service;

import com.ddd.context.Parameters;
import com.ddd.entity.Article;
import com.ddd.entity.Commision;
import com.ddd.entity.Journal;
import com.ddd.entity.Publisher;
import com.ddd.util.HibernateUtil;
import com.ddd.util.Util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class CommisionService extends BaseService {

    private Parameters para;
    private LogService logService;

    public CommisionService(HttpServletRequest request) {
        para = new Parameters(request);
        logService = new LogService(request);
        this.request = request;
    }

    public Commision load(String id) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();

        Commision commision = (Commision) session.load(Commision.class, id);
        //Hibernate.initialize(journal);

        tx.commit();
        session.close();

        return commision;
    }

    public ArrayList loadAll() {
        ArrayList result = new ArrayList();
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        Criteria criteria = session.createCriteria(Commision.class);
        criteria.addOrder(Order.desc("year"));

        Iterator iter = criteria.list().iterator();
        while (iter.hasNext()) {
            result.add(iter.next());
        }
        tx.commit();
        session.close();
        para.setTotalSize(result.size());
        return result;
    }

    public void save(Commision commision) {
        // get id first
        IDService idService = new IDService();
        commision.setId(idService.getNextID("commision"));

        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        commision.setCid(para.getUsername());
        commision.setCtime(Util.getTodayWithTime());
        session.save(commision);
        tx.commit();
        session.close();
    }

    public void update(Commision commision) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        commision.setUid(para.getUsername());
        commision.setUtime(Util.getTodayWithTime());
        session.update(commision);
        tx.commit();
        session.close();
    }

    public void delete(Commision commision) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        session.delete(commision);
        tx.commit();
        session.close();
    }

    public ArrayList calculate(String publisherID) {
        ArrayList result = new ArrayList();

        // load commision
        Commision commision = this.loadByYear(Util.getThisYear());

        int year = Integer.parseInt(commision.getYear());
        double amount = Double.parseDouble(commision.getAmount());
        double currAmount = amount * Double.parseDouble(commision.getCurrCommision()) / 100;
        double postAmount = amount * Double.parseDouble(commision.getPostCommision()) / 100;

        // load all journals belong to this publisher
        JournalService journalService = new JournalService(request);
        ArrayList<Journal> journals = journalService.loadByPublisher(publisherID);

        PublisherService publisherService = new PublisherService(request);
        ArticleService articleService = new ArticleService(request);
        double totalArticles = Double.parseDouble(String.valueOf(articleService.loadAll().size()));

        for (Journal j : journals) {
            long currArticle = 0;
            long postArticle = 0;

            // get publisher name
            Publisher publisher = publisherService.load(j.getFkPublisherId());

            ArrayList<Article> articles = articleService.loadByJournal(j.getId());

            for (Article a : articles) {
                if (Util.isNotBlank(a.getCurrJournal()) && a.getCurrJournal().equals("on")) {
                    currArticle++;
                } else {
                    postArticle++;
                }
            }

            HashMap map = new HashMap();
            map.put("journalName", j.getName());
            map.put("publisher", publisher.getName());
            map.put("totalArticle", new Long(currArticle + postArticle));
            map.put("currArticleAmount", new Double(currArticle / totalArticles * currAmount));
            map.put("postArticleAmount", new Double(postArticle / totalArticles * postAmount));
            map.put("totalAmount", new Double((postArticle / totalArticles * postAmount)) + (currArticle / totalArticles * currAmount));

            result.add(map);
        }

        return result;
    }

    public Commision loadByYear(String year) {
        ArrayList result = new ArrayList();
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        Transaction tx = session.beginTransaction();
        Criteria criteria = session.createCriteria(Commision.class);
        criteria.add(Restrictions.eq("year", year));

        Iterator iter = criteria.list().iterator();


        while (iter.hasNext()) {
            result.add(iter.next());
        }

        tx.commit();

        session.close();
        //para.setTotalSize(result.size());


        if (result.size()
                != 0) {
            return (Commision) result.get(0);
        } else {
            return null;
        }
    }
}
